package com.mike.bdb.ui;

import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.ArrayUtils;
import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TextCellEditor;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.custom.CTabFolder2Adapter;
import org.eclipse.swt.custom.CTabFolderEvent;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.ColorDialog;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mike.bdb.manager.DBManager;
import com.mike.bdb.ui.provider.table.MikeTableCellModifier;
import com.mike.bdb.ui.provider.table.MikeTableContentProvider;
import com.mike.bdb.ui.provider.table.MikeTableLabelProvider;
import com.mike.bdb.ui.provider.table.MikeTableViewerSorter;
import com.mike.bdb.ui.provider.tree.MikeTreeContentProvider;
import com.mike.bdb.ui.provider.tree.MikeTreeLabelProvider;
import com.mike.bdb.ui.provider.tree.TreeNode;
import com.mike.bdb.ui.provider.tree.TreeSelectionUtil;
import com.mike.bdb.util.BackThread;
import com.mike.bdb.util.DPLBDBNameUtil;
import com.mike.bdb.util.DataCurrent;
import com.mike.bdb.util.Folder;
import com.mike.bdb.util.ImageManager;
import com.mike.bdb.util.ReflectUtil;
import com.mike.bdb.util.DPLBDBNameUtil.KeyName;
import com.mike.swt.util.ShellUtil;
import com.sleepycat.persist.EntityCursor;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.SecondaryIndex;

public class MainWindow {

	private static final Logger LOG = LoggerFactory.getLogger(MainWindow.class);
	public static final String SPLIT_PATH_CLASS = " -> ";
	private static final int PAGE_BUTTON_WIDTH = 45;
	private static final int CRUD_BUTTON_WIDTH = 75;
	protected Shell	motherland;
	private Image	logo_mike;
	private TreeViewer	treeViewer;
	private Text currentDatabaseName;
	private SashForm sashFormData;
	private CTabFolder tabTabFolder;
	private NewEntityDialog newEntityDialog;
	private ImportDialog importDialog;
	private ExportDialog exportDialog;
	private SecondaryEntityTable secondaryEntityTable;
	private BugReport bugReport;
	private HistoryUpdate historyUpdate;
	private SelectDialog selectDialog;
	private About about;
	private static MainWindow window;
	private static List<Map<CTabItem, TableViewer>> allTabItem = new ArrayList<Map<CTabItem, TableViewer>>();
	private FormData formData_1;
	private Label pageIndex;
	private HashMap<String, Type> methodReturnMap;
	private QueryEntityDialog queryDialog;
	private QueryEntityByKeyDialog queryByKeyDialog;
	private QueryConditionEntityTable	queryConditionEntityTable;
	private QueryPKEntityTable	queryPKEntityTable;
	private static volatile boolean isLinkSelect = true;

	/**
	 * Launch the application.
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			window = new MainWindow();
			window.open();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void resetPageIndex() {
		//TODO <!分页> 设置当前页标签
		int index = DataCurrent.getInstance().getPageInfo().getIndex() + 1;
		
		if(null != pageSpinner) {
			if(!pageSpinner.isFocusControl()) {
				pageSpinner.setSelection(index);
			}
		}
		
		if(null != pageIndex) {
			pageIndex.setText( " 共 " +
					DataCurrent.getInstance().getPageInfo().getMaxPage()
					+ " 页");
		}
		
		MikeTableContentProvider.cleanButton();
	}
	
	/**
	 * Open the window.
	 */
	public void open() {
		Display display = Display.getDefault();
		createContents();
		ShellUtil.setCenter(motherland);
		motherland.open();
		motherland.layout();
		while (!motherland.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
	}
	
	/**
	 * 第一页
	 */
	private void apexLeft() {
		//TODO <!分页> 第一页
//		DataCurrent.getInstance().setCurrentPage(0);
		DataCurrent.getInstance().getPageInfo().setIndex(0);
		resetPageIndex();
		refreshActiveViewer();
	}
	
	/**
	 * 上一页
	 */
	private void leftPage() {
		//TODO <!分页> 上一页
		int currentPage = DataCurrent.getInstance().getPageInfo().getIndex();
		if(currentPage > 0) {
			DataCurrent.getInstance().getPageInfo().setIndex(currentPage - 1);
		}
		resetPageIndex();
		refreshActiveViewer();
	}
	
	/**
	 * 改变当前页数
	 * @param text
	 */
	private void changePageCount(String text) {
		//TODO <!分页> 改变当前页数 
		if(null == text) return;
		
		int maxPage = DataCurrent.getInstance().getPageInfo().getMaxPage();
		
		int parseInt = 0;
		
		try {
			parseInt = Integer.parseInt(text);
		} catch (Exception e) {
			//eat it.
		}
		
		if(parseInt > maxPage) {
			parseInt = maxPage;
		}
		
		if(parseInt <= 0) {
			parseInt = 1;
		}
		
		parseInt = parseInt > 0 ? parseInt - 1 : parseInt;
		
		DataCurrent.getInstance().getPageInfo().setIndex(parseInt);
		resetPageIndex();
		refreshActiveViewer();
	}
	
	/**
	 * 最后一页
	 */
	private void apexRight() {
		//TODO <!分页> 最后一页
		DataCurrent.getInstance().getPageInfo().setIndex(
				DataCurrent.getInstance().getPageInfo().getMaxPage() - 1);
		resetPageIndex();
		refreshActiveViewer();
	}
	
	/**
	 * 下一页
	 */
	private void rightPage() {
		//TODO <!分页> 下一页
		int currentPage = DataCurrent.getInstance().getPageInfo().getIndex();
		int maxPage = DataCurrent.getInstance().getPageInfo().getMaxPage();
		if(++currentPage < maxPage) {
			DataCurrent.getInstance().getPageInfo().setIndex(currentPage);
		}
		resetPageIndex();
		refreshActiveViewer();
	}
	
	/**
	 * 改变当前数据库
	 */
	private void changeCurretDb() {
		
		if(null == tabTabFolder.getSelection()) return;
		
		String currentDB = tabTabFolder.getSelection().getText();
		
		if (LOG.isDebugEnabled()) {
			LOG.debug("Current DB > " + currentDB);
		}
		
		Object data = tabTabFolder.getSelection().getData();
		
		if(null != data) {
			String dbStr = TreeSelectionUtil.getDatabaseName(data.toString());
			if (LOG.isDebugEnabled()) {
				LOG.debug("Current Data > " + dbStr);
			}
			
			DBManager.getInstance().updateHome(dbStr);
		}
		
		Class<?> classByName = DPLBDBNameUtil.getInstance().getClassByName(DPLBDBNameUtil.currentPackageName + "." + currentDB);
		
		if(null == classByName) return;
		
		DataCurrent.getInstance().curStoreClazz = classByName.getName();
		
		if (LOG.isDebugEnabled()) {
			LOG.debug("Current DB String > " + DataCurrent.getInstance().curStoreClazz);
		}
		
		DPLBDBNameUtil.KeyName keyName = DPLBDBNameUtil.getInstance().newKeyName(
				currentDB, currentDB, DataCurrent.getInstance().curStoreClazz);
		
		linkUpdataTreeSelected();
		
		//TODO <!分页> 改变数据库时归零
		DataCurrent.getInstance().getPageInfo().setIndex(0);
		
		updataDataCurrent(keyName);
		resetPageIndex();
		refreshActiveViewer();
	}
	
	/**
	 * 联动
	 */
	private void linkUpdataTreeSelected() {
		if(null == treeViewer) return;
		if(!isLinkSelect) return;
		String curDataBasePath = DataCurrent.getInstance().curDataBasePath;
		if(null == curDataBasePath) return;
		treeViewer.getTree().setFocus();
		TreeItem[] items = treeViewer.getTree().getItems();
		for (TreeItem treeItem : items) {
			String string = treeItem.getData().toString();
			if(string.equals(curDataBasePath)) {
				items = treeItem.getItems();
				for (TreeItem item : items) {
					string = item.getData().toString();
					string = TreeSelectionUtil.getDatabaseClassName(string);
					if(string.equals(DataCurrent.getInstance().curStoreClazz.toString()) ) {
						treeViewer.getTree().setSelection(item);
						updataCurrentDatabaseNameInfo("[" + item.getData().toString() + "]");
					}
				}
			}
		}
	}

	private void updataCurrentDatabaseNameInfo(String string) {
		if(null == string) return;
		string = TreeSelectionUtil.getName(string);
		String databaseName = TreeSelectionUtil.getDatabaseName(string);
		String clazzName = TreeSelectionUtil.getDatabaseClassName(string);
		currentDatabaseName.setText(databaseName + SPLIT_PATH_CLASS + clazzName);
	}
	
	/**
	 * 计算分页数据
	 * @param keyName
	 */
	private void updataDataCurrent(KeyName keyName) {
		
		Class<?> classByKeyName = ReflectUtil.getClassBy(keyName);
		
		if(null == classByKeyName) return;
		
		EntityStore store = DBManager.getInstance().getEntityStore();
		
		EntityCursor<?> entities = null;
			if(keyName.isSec()) {
				SecondaryIndex<String, String, ?> secondaryIndex = 
					store.getSecondaryIndex(
							store.getPrimaryIndex(String.class, classByKeyName),
							String.class,
							keyName.getSuffix());
				entities = secondaryIndex.entities();
			} else {
				//TODO ★ Berkeley DB entities 
				Class pkClass = ReflectUtil.getPKClass(classByKeyName);
				long count = store.getPrimaryIndex(pkClass, classByKeyName).count();
				
				//TODO <!分页> 更新总记录数
				DataCurrent.getInstance().getPageInfo().setCount((int) count);
			}
		try {
		} finally {
			if(null != entities) {
				entities.close();
			}
		}
	}
	
	/**
	 * 删除
	 */
	private void deleteSelect() {
		if(null == tabTabFolder) return;
		CTabItem selection = tabTabFolder.getSelection();
		if(null == selection) return;
		Table table = (Table) selection.getControl();
		if(null == table) return;
		int selectionIndex = table.getSelectionIndex();
		TableItem[] selectionSize = table.getSelection();
		if(null == selectionSize || selectionSize.length <= 0) return;
		
		String curStoreClazz = DataCurrent.getInstance().curStoreClazz;
		Class<Object> classBy = ReflectUtil.getClassBy(curStoreClazz);
		Method method = ReflectUtil.getPKGetMethod(classBy);
		if (LOG.isDebugEnabled()) {
			LOG.debug("开始删除记录...");
		}
		for (TableItem tableItem:selectionSize) {
			try {
				Object invoke = method.invoke(tableItem.getData(), null);
				Class pkClass = ReflectUtil.getPKClass(classBy);
				//TODO ★ Berkeley DB delete
				DBManager.getInstance().getPKStore(pkClass, classBy).delete(invoke);
			} catch (Exception e) {
				if(LOG.isDebugEnabled()) 
					LOG.debug("删除失败 " + e.getMessage());
			}
		}
		
		refreshActiveViewer();
		int cur = selectionIndex >= table.getItemCount() ? table.getItemCount() - 1 : selectionIndex;
		table.setSelection(cur);
		resetPageIndex();
	}
	
	/** 刷新活动表格 */
	public void refreshActiveViewer() {
		
		for (Map<CTabItem, TableViewer> eachMap : allTabItem) {
			if(null == eachMap) continue;
			Iterator<Entry<CTabItem, TableViewer>> it = eachMap.entrySet().iterator();
			while (it.hasNext()) {
				Entry<CTabItem, TableViewer> next = it.next();
				if(null == next.getKey()) continue;
				CTabItem key = next.getKey();
				if(key.isDisposed()) {
					it.remove();
					continue;
				}
				String selectDBName = key.getText();
				if(DataCurrent.getInstance().curStoreClazz.endsWith(selectDBName)){
					if(next.getValue().getTable().isDisposed()) {
						it.remove();
						continue;
					}
					
					TableViewer value = next.getValue();
					initColor(value);
					value.refresh();
				}
			}
		}
	}
	
	/**
	 * Create contents of the window.
	 */
	protected void createContents() {
		motherland = new Shell();
		logo_mike = ImageManager.getImage(ImageManager.LOGO_MING);
		motherland.setImage(logo_mike);
		
		//TODO 主窗口大小
		motherland.setSize(1024, 650);
		
		motherland.setText(Messages.getString("Motherland.motherland.text") + " " + DataCurrent.VERSION);
		motherland.setLayout(new FillLayout(SWT.HORIZONTAL));
		{
			Menu menu = new Menu(motherland, SWT.BAR);
			motherland.setMenuBar(menu);
			{
				MenuItem menuItem = new MenuItem(menu, SWT.CASCADE);
				menuItem.setImage(ImageManager.getImage(ImageManager.ICON_BOOK));
				menuItem.setText(Messages.getString("MainWindow.menuItem.text_2")); //$NON-NLS-1$
				{
					Menu menu_1 = new Menu(menuItem);
					menuItem.setMenu(menu_1);
					{
						MenuItem menuItem_1 = new MenuItem(menu_1, SWT.NONE);
						menuItem_1.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								if(!selectDialog.isOpen()) {
									selectDialog.open();
								}
							}
						});
						menuItem_1.setImage(ImageManager.getImage(ImageManager.ICON_BOOK_OPEN));
						menuItem_1.setText(Messages.getString("MainWindow.menuItem_1.text")); //$NON-NLS-1$
					}
					{
						MenuItem menuItem_1 = new MenuItem(menu_1, SWT.NONE);
						menuItem_1.setEnabled(false);
						menuItem_1.setImage(ImageManager.getImage(ImageManager.ICON_BOOK_ADD));
						menuItem_1.setText(Messages.getString("MainWindow.menuItem_1.text_1")); //$NON-NLS-1$
					}
					{
						MenuItem mntme = new MenuItem(menu_1, SWT.NONE);
						mntme.setImage(ImageManager.getImage(ImageManager.ICON_EXIT));
						mntme.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								motherland.close();
							}
						});
						mntme.setText(Messages.getString("MainWindow.mntme.text")); //$NON-NLS-1$
					}
				}
			}
			{
				MenuItem menuItem = new MenuItem(menu, SWT.CASCADE);
				menuItem.setText(Messages.getString("MainWindow.menuItem.text_6")); //$NON-NLS-1$
				menuItem.setImage(ImageManager.getImage(ImageManager.ICON_FIND));
				{
					Menu menu_1 = new Menu(menuItem);
					menuItem.setMenu(menu_1);
					{
						MenuItem mntmp = new MenuItem(menu_1, SWT.NONE);
						mntmp.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								queryByKey();
							}
						});
						mntmp.setText(Messages.getString("MainWindow.mntmp.text")); //$NON-NLS-1$
						mntmp.setImage(ImageManager.getImage(ImageManager.ICON_FIND_BY_KEY));
					}
					{
						MenuItem mntms = new MenuItem(menu_1, SWT.NONE);
						mntms.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								query();
							}
						});
						mntms.setText(Messages.getString("MainWindow.mntms.text")); //$NON-NLS-1$
						mntms.setImage(ImageManager.getImage(ImageManager.ICON_FIND_KEY2));
					}
				}
			}
			{
				MenuItem mntmv = new MenuItem(menu, SWT.CASCADE);
				mntmv.setText(Messages.getString("MainWindow.mntmv.text")); //$NON-NLS-1$
				mntmv.setImage(ImageManager.getImage(ImageManager.ICON_COLOR_WHEEL));
				{
					Menu menu_2 = new Menu(mntmv);
					mntmv.setMenu(menu_2);
					{
						MenuItem menuItem = new MenuItem(menu_2, SWT.NONE);
						menuItem.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								ColorDialog color = new ColorDialog(motherland, SWT.NONE);
								RGB odd = color.open();
								if(null != odd) {
									currentColorOdd = new Color(Display.getCurrent(), odd);
									refreshActiveViewer();
								}
							}
						});
						menuItem.setText(Messages.getString("MainWindow.menuItem.text_4")); //$NON-NLS-1$
						menuItem.setImage(ImageManager.getImage(ImageManager.ICON_RAINBOW));
					}
					{
						MenuItem menuItem = new MenuItem(menu_2, SWT.NONE);
						menuItem.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								ColorDialog color = new ColorDialog(motherland, SWT.NONE);
								RGB even = color.open();
								if(null != even) {
									currentColorEven = new Color(Display.getCurrent(), even);
									refreshActiveViewer();
								}
							}
						});
						menuItem.setText(Messages.getString("MainWindow.menuItem.text_5")); //$NON-NLS-1$
						menuItem.setImage(ImageManager.getImage(ImageManager.ICON_RAINBOW));
					}
				}
			}
			{
				MenuItem menuItem = new MenuItem(menu, SWT.CASCADE);
				menuItem.setText(Messages.getString("MainWindow.menuItem.text_3")); //$NON-NLS-1$
				menuItem.setImage(ImageManager.getImage(ImageManager.ICON_TAG_GREEN));
				{
					Menu menu_1 = new Menu(menuItem);
					menuItem.setMenu(menu_1);
					{
						MenuItem mntmq = new MenuItem(menu_1, SWT.NONE);
						mntmq.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								if(!bugReport.isOpen()) {
									bugReport.open();
								}
							}
						});
						mntmq.setText(Messages.getString("MainWindow.mntmq.text")); //$NON-NLS-1$
						mntmq.setImage(ImageManager.getImage(ImageManager.ICON_BUG));
					}
					{
						MenuItem menuItem_1 = new MenuItem(menu_1, SWT.NONE);
						menuItem_1.setText(Messages.getString("MainWindow.menuItem_1.text_2")); //$NON-NLS-1$
						menuItem_1.setImage(ImageManager.getImage(ImageManager.ICON_PLUGIN));
						menuItem_1.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								if(!historyUpdate.isOpen()) {
									historyUpdate.open();
								}
							}
						});
						
					}
					{
						MenuItem menuItem_1 = new MenuItem(menu_1, SWT.NONE);
						menuItem_1.setText(Messages.getString("MainWindow.menuItem_1.text_3")); //$NON-NLS-1$
						menuItem_1.setImage(ImageManager.getImage(ImageManager.ICON_COMMENT_EDIT));
						menuItem_1.addSelectionListener(new SelectionAdapter() {
							@Override
							public void widgetSelected(SelectionEvent e) {
								if(!about.isOpen()) {
									about.open();
								}
							}
						});
					}
				}
			}
		}
		{
			Composite base = new Composite(motherland, SWT.NONE);
			base.setLayout(new FormLayout());
			{
				sashFormData = new SashForm(base, SWT.NONE);
				{
					formData_1 = new FormData();
					formData_1.top = new FormAttachment(0, 10);
					formData_1.left = new FormAttachment(0, 10);
					sashFormData.setLayoutData(formData_1);
				}
				{
					Composite dir_composite = new Composite(sashFormData, SWT.NONE);
					dir_composite.setLayout(new GridLayout(1, false));
					{
						dirTabFolder = new CTabFolder(dir_composite, SWT.BORDER);
						initTabFolderColorAndMenu(dirTabFolder);
						{
							GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
							gridData.heightHint = 485;
							dirTabFolder.setLayoutData(gridData);
						}
						dirTabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
						{
							CTabItem tabItem = new CTabItem(dirTabFolder, SWT.NONE);
							tabItem.setText(Messages.getString("MainWindow.tabItem.text")); //$NON-NLS-1$
							{
								treeViewer = new TreeViewer(dirTabFolder, SWT.BORDER /*| SWT.MULTI*/);
								Tree tree = treeViewer.getTree();
								tabItem.setControl(tree);
								treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
									public void selectionChanged(SelectionChangedEvent e) {
										updataCurrentDatabaseNameInfo(e.getSelection().toString());
									}
									
								});
								treeViewer.addDoubleClickListener(new IDoubleClickListener() {
									public void doubleClick(DoubleClickEvent e) {
										String databaseName = e.getSelection().toString();
										if(LOG.isDebugEnabled()) {
											LOG.debug("DoubleClick on -> " + databaseName);
										}
										appendTableData(databaseName);
									}
								});
								initTree(treeViewer);
							}
							selectDialog = new SelectDialog(motherland, treeViewer);
						}
					}
					{
						Composite dir_composite_btn = new Composite(dir_composite, SWT.NONE);
						dir_composite_btn.setLayout(new GridLayout(1, false));
						{
							GridData gridData = new GridData(SWT.FILL, SWT.CENTER, false, false, 1, 1);
							gridData.widthHint = 165;
							dir_composite_btn.setLayoutData(gridData);
						}
						{
							final Button button = new Button(dir_composite_btn, SWT.TOGGLE);
							button.setEnabled(false);
							button.addSelectionListener(new SelectionAdapter() {
								@Override
								public void widgetSelected(SelectionEvent e) {
									if(isLinkSelect) {
										isLinkSelect = false;
										button.setImage(ImageManager.getImage(ImageManager.ICON_LINK_BREAK));
									} else {
										isLinkSelect = true;
										button.setImage(ImageManager.getImage(ImageManager.ICON_LINK));
									}
									linkUpdataTreeSelected();
								}
							});
							button.setText(Messages.getString("MainWindow.button.text_4")); //$NON-NLS-1$
							button.setImage(ImageManager.getImage(ImageManager.ICON_LINK));
						}
					}
				}
				{
					Composite data_composite = new Composite(sashFormData, SWT.NONE);
					
					data_composite.setLayout(new GridLayout(1, false));
					{
						tabTabFolder = new CTabFolder(data_composite, SWT.NONE);
						initTabFolderColorAndMenu(tabTabFolder);
						tabTabFolder.addMouseListener(new MouseAdapter() {
							@Override
							public void mouseUp(MouseEvent e) {
								changeCurretDb();
							}
						});
						{
							GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
							gridData.heightHint = 485;
							tabTabFolder.setLayoutData(gridData);
						}
						tabTabFolder.setLayoutData(new GridData(GridData.FILL_BOTH));
					}
					{
						Composite data_composite_btn = new Composite(data_composite, SWT.NONE);
						data_composite_btn.setLayout(new GridLayout(13, false));
						{
							Button btnq = new Button(data_composite_btn, SWT.NONE);
							{
								GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
								gridData.widthHint = CRUD_BUTTON_WIDTH;
								btnq.setLayoutData(gridData);
							}
							btnq.addSelectionListener(new SelectionAdapter() {
								@Override
								public void widgetSelected(SelectionEvent arg0) {
									query();
								}
							});
							btnq.setText(Messages.getString("MainWindow.btnq.text")); //$NON-NLS-1$
							btnq.setImage(ImageManager.getImage(ImageManager.ICON_FIND_KEY2));
						}
						{
							Button button = new Button(data_composite_btn, SWT.NONE);
							{
								GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
								gridData.widthHint = CRUD_BUTTON_WIDTH;
								button.setLayoutData(gridData);
							}
							button.addSelectionListener(new SelectionAdapter() {
								@Override
								public void widgetSelected(SelectionEvent e) {
									if(!newEntityDialog.isOpen()) {
										newEntityDialog.open();
									}
								}
							});
							button.setText(Messages.getString("MainWindow.button.text_1")); //$NON-NLS-1$
							button.setImage(ImageManager.getImage(ImageManager.ICON_ADD));
						}
						{
							Button button = new Button(data_composite_btn, SWT.NONE);
							{
								GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
								gridData.widthHint = CRUD_BUTTON_WIDTH;
								button.setLayoutData(gridData);
							}
							button.setText(Messages.getString("MainWindow.button.text_2")); //$NON-NLS-1$
							button.setImage(ImageManager.getImage(ImageManager.ICON_CANCEL));
							button.addSelectionListener(new SelectionAdapter() {
								@Override
								public void widgetSelected(SelectionEvent e) {
									deleteSelect();
								}
							});
							{
								Button btnr = new Button(data_composite_btn, SWT.NONE);
								btnr.addSelectionListener(new SelectionAdapter() {
									@Override
									public void widgetSelected(SelectionEvent arg0) {
										refreshActiveViewer();
									}
								});
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = CRUD_BUTTON_WIDTH;
									btnr.setLayoutData(gridData);
								}
								btnr.setText(Messages.getString("MainWindow.btnr.text")); //$NON-NLS-1$
								btnr.setImage(ImageManager.getImage(ImageManager.ICON_DATABASE_REFRESH));
							}
							{
								Label label = new Label(data_composite_btn, SWT.NONE);
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = 30;
									label.setLayoutData(gridData);
								}
								if(LOG.isDebugEnabled()) LOG.debug(label.getText());
							}
							{
								Button button_1 = new Button(data_composite_btn, SWT.NONE);
								button_1.addSelectionListener(new SelectionAdapter() {
									@Override
									public void widgetSelected(SelectionEvent e) {
										apexLeft();
									}
									
								});
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = PAGE_BUTTON_WIDTH;
									button_1.setLayoutData(gridData);
								}
								button_1.setText(Messages.getString("MainWindow.button_1.text")); //$NON-NLS-1$
							}
							{
								Button button_left = new Button(data_composite_btn, SWT.NONE);
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = PAGE_BUTTON_WIDTH;
									button_left.setLayoutData(gridData);
								}
								button_left.addSelectionListener(new SelectionAdapter() {
									@Override
									public void widgetSelected(SelectionEvent e) {
										leftPage();
									}
									
								});
								button_left.setText(Messages.getString("MainWindow.button_left.text")); //$NON-NLS-1$
								
							}
							{
								Label label = new Label(data_composite_btn, SWT.NONE);
								label.setAlignment(SWT.RIGHT);
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = 24;
									label.setLayoutData(gridData);
								}
								label.setText(Messages.getString("MainWindow.label.text")); //$NON-NLS-1$
							}
							{
								pageSpinner = new Spinner(data_composite_btn, SWT.BORDER);
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = 30;
									pageSpinner.setLayoutData(gridData);
								}
								pageSpinner.addSelectionListener(new SelectionAdapter() {
									@Override
									public void widgetSelected(SelectionEvent e) {
										changePageCount(pageSpinner.getText());
									}
								});
								
								//TODO <!分页> 初始化每页记录数
								pageSpinner.setMinimum(1);
								pageSpinner.setMaximum(Integer.MAX_VALUE);
								pageSpinner.setTextLimit(Integer.MAX_VALUE);
							}
							{
								Label label = new Label(data_composite_btn, SWT.NONE);
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = 24;
									label.setLayoutData(gridData);
								}
								label.setText(Messages.getString("MainWindow.label.text_1")); //$NON-NLS-1$
							}
							{
								Button button_rigth = new Button(data_composite_btn, SWT.NONE);
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = PAGE_BUTTON_WIDTH;
									button_rigth.setLayoutData(gridData);
								}
								button_rigth.addSelectionListener(new SelectionAdapter() {
									@Override
									public void widgetSelected(SelectionEvent e) {
										rightPage();
									}
								});
								button_rigth.setText(Messages.getString("MainWindow.button_rigth.text")); //$NON-NLS-1$
							}
							{
								Button button_1 = new Button(data_composite_btn, SWT.NONE);
								button_1.addSelectionListener(new SelectionAdapter() {
									@Override
									public void widgetSelected(SelectionEvent e) {
										apexRight();
									}
								});
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = PAGE_BUTTON_WIDTH;
									button_1.setLayoutData(gridData);
								}
								button_1.setText(Messages.getString("MainWindow.button_1.text_1")); //$NON-NLS-1$
							}
							
							{
								pageIndex = new Label(data_composite_btn, SWT.NONE);
								pageIndex.setAlignment(SWT.CENTER);
								{
									GridData gridData = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
									gridData.widthHint = 80;
									pageIndex.setLayoutData(gridData);
								}
								resetPageIndex();
							}
						}
					}
				}
			}
			{
				Composite composite = new Composite(base, SWT.NONE);
				formData_1.right = new FormAttachment(composite, 0, SWT.RIGHT);
				formData_1.bottom = new FormAttachment(composite, -6);
				sashFormData.setWeights(new int[] {200, 769});
				
				composite.setLayout(new FillLayout());
					currentDatabaseName = new Text(composite, SWT.BORDER);
					currentDatabaseName.setEditable(false);
					currentDatabaseName.setText("not database selected.");
				{
					FormData formData = new FormData();
					formData.left = new FormAttachment(0, 10);
					formData.right = new FormAttachment(100, -10);
					formData.bottom = new FormAttachment(100, -10);
					composite.setLayoutData(formData);
				}
			}
		}
		
		motherland.addShellListener(new ShellAdapter() {
			public void shellClosed(ShellEvent e) {
				MessageBox mb = new MessageBox(motherland, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
				mb.setText(Messages.getString("Motherland.motherland.text")
						+ " " 
						+ DataCurrent.VERSION);
				mb.setMessage("您确定退出吗?");
				int rc = mb.open();
				e.doit = (rc == SWT.OK);
				DBManager.getInstance().release();
			}
		});
		
		//TODO Berkeley DB Visual Editor other sub window here.
		newEntityDialog = new NewEntityDialog(motherland, this);
		queryDialog = new QueryEntityDialog(motherland, this);
		queryByKeyDialog = new QueryEntityByKeyDialog(motherland, this);
		queryConditionEntityTable = new QueryConditionEntityTable(motherland);
		queryPKEntityTable = new QueryPKEntityTable(motherland);
		importDialog = new ImportDialog(motherland, this);
		exportDialog = new ExportDialog(motherland);
		secondaryEntityTable = new SecondaryEntityTable(motherland);
		bugReport = new BugReport(motherland);
		historyUpdate = new HistoryUpdate(motherland);
		about = new About(motherland);
	}

	private void initTabFolderColorAndMenu(CTabFolder tabFolder) {
		if(null == tabFolder) return;
		tabFolder.setTabHeight(24);
		tabFolder.setSimple(false);
		tabFolder.setBorderVisible(true);
        Display display = Display.getCurrent(); 
        int colorCount = 3;
        Color[] colors = new Color[colorCount]; 
        colors[0] = display.getSystemColor(SWT.COLOR_TITLE_BACKGROUND); 
        colors[1] = display.getSystemColor(SWT.COLOR_TITLE_BACKGROUND_GRADIENT); 
        colors[2] = colors[0]; 
        int[] percents = new int[colorCount - 1]; 
        percents[0] = 4; 
        percents[1] = 60; 
        tabFolder.setSelectionBackground(colors, percents, true); 
        tabFolder.setSelectionForeground(display.getSystemColor(SWT.COLOR_TITLE_FOREGROUND));
        initTabFolderMenu();
	}

	private void initTabFolderMenu() {
		if(null == tabTabFolder) return;
		final Menu menu = new Menu(motherland, SWT.POP_UP);
		MenuItem menuItem_closeOther = new MenuItem(menu, SWT.PUSH);
		menuItem_closeOther.setText("关闭其他");
		menuItem_closeOther.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				CTabItem[] items = tabTabFolder.getItems();
				Object selection = tabTabFolder.getSelection().getData();
				if(null == selection) return;
				for (CTabItem item : items) {
					Object data = item.getData();
					if(null != data) {
						String string = data.toString();
						String select = selection.toString();
						System.out.println(string);
						System.out.println(select);
						if(string.equals(select)) {
							continue;
						}
						DataCurrent.openTableViewers.remove(string);
						item.dispose();
					}
						
				}
			}
			
		});
		
		MenuItem menuItem_closeAll = new MenuItem(menu, SWT.PUSH);
		menuItem_closeAll.setText("关闭所有");
		menuItem_closeAll.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				CTabItem[] items = tabTabFolder.getItems();
				for (CTabItem item : items) {
					item.dispose();
					DataCurrent.openTableViewers.clear();
				}
			}
			
		});
		
		tabTabFolder.setMenu(menu);
		menu.addMenuListener(new MenuAdapter() {
			@Override
			public void menuShown(MenuEvent e) {
				Point p = Display.getDefault().getCursorLocation();
				p = tabTabFolder.toControl(p);
				CTabItem item = tabTabFolder.getItem(p);
				if(null == item) {
					menu.setVisible(false);
					return;
				}
			}
		});
	}

	/**
	 * 应用程序初始化时自动载入所在目录的Berkeley DB 数据
	 * @param tree
	 */
	private void initTree(TreeViewer tree) {
		if(null != tree) {
			tree.setContentProvider(new MikeTreeContentProvider());
			tree.setLabelProvider(new MikeTreeLabelProvider());
			tree.setInput(null);
			initTreeListener();
			initTreeLeafMenu();
		}
	}
	
	/** 树选择变更监听器 */
	private void initTreeListener() {
		if(null == treeViewer) return;
		treeViewer.addSelectionChangedListener(new ISelectionChangedListener() {
			@Override
			public void selectionChanged(SelectionChangedEvent e) {
				ISelection selection = e.getSelection();
				if(null == selection) return;
				String databaseName = TreeSelectionUtil.getName(selection.toString());
				if(null == databaseName) return;
				DPLBDBNameUtil.KeyName keyName = DPLBDBNameUtil.getInstance().getKeyNameByDatabaseName(databaseName);
				if(null == keyName) return;
				if(null == keyName.getCurStoreClazz()) return;
				if(!isLinkSelect) return;
				
				
				//TODO 关闭树到表的联动，编辑器刷新问题。
//				boolean containsKey = DataCurrent.openTableViewers.containsKey(databaseName);
//				if(containsKey) {
//					changeSelectedTableItem(databaseName);
//					updataDataCurrent(keyName);
//					resetPageIndex();
//					refreshActiveViewer();
//					DataCurrent.getInstance().curStoreClazz = keyName.getCurStoreClazz();
//					return;
//				}
				
				
				
			}
		});
	}

	/** 树叶菜单 */
	private void initTreeLeafMenu() {
		
		if(null == treeViewer) return;
		
		final Menu menu_leaf = new Menu(motherland, SWT.POP_UP);
		
		menu_leaf.addMenuListener(new MenuAdapter() {
			@Override
			public void menuShown(MenuEvent e) {
				Point p = Display.getDefault().getCursorLocation();
				p = treeViewer.getTree().toControl(p);
				TreeItem item = treeViewer.getTree().getItem(p);
				if(null == item) {
					menu_leaf.setVisible(false);
					return;
				}
				Object data = item.getData();
				if(null != data) {
					if(data instanceof TreeNode) {
						TreeNode node = (TreeNode) data;
						if(node.isRoot()) {
							menu_leaf.setVisible(false);
							return;
						}
					}
				}
			}
		});
		
		MenuItem exportData = new MenuItem(menu_leaf, SWT.PUSH);
		exportData.setText("导出数据");
		exportData.setImage(ImageManager.getImage(ImageManager.ICON_DATABASE_GO));
		exportData.addSelectionListener(new SelectionAdapter() {
			
			@Override
			public void widgetSelected(SelectionEvent e) {
				String oldCurStoreClazz = DataCurrent.getInstance().curStoreClazz;
				TreeItem[] selection = treeViewer.getTree().getSelection();
				if(LOG.isDebugEnabled()) {
					LOG.debug(ArrayUtils.toString(selection));
				}
				
				if(null == selection) return;
				TreeItem treeItem = selection[0];
				if(treeItem.getData() instanceof TreeNode) {
					TreeNode treeNode = (TreeNode) treeItem.getData();
					String databaseName = treeNode.toString();
					if(null == databaseName) return;
					String dbStr = TreeSelectionUtil.getDatabaseName(databaseName);
					DBManager.getInstance().updateHome(dbStr);
					DPLBDBNameUtil.KeyName keyName = DPLBDBNameUtil.getInstance().getKeyNameByDatabaseName(databaseName);
					if(null == keyName) return;
					if(null == keyName.getCurStoreClazz()) return;
					DataCurrent.getInstance().curStoreClazz = keyName.getCurStoreClazz();
				}
				
				if(!exportDialog.isOpen()) {
					exportDialog.open();
					DataCurrent.getInstance().curStoreClazz = oldCurStoreClazz;
					System.out.println(DataCurrent.getInstance().curStoreClazz);
				}
			}
			
		});
		
		MenuItem importData = new MenuItem(menu_leaf, SWT.PUSH);
		importData.setText("导入数据");
		importData.setImage(ImageManager.getImage(ImageManager.ICON_DATABASE_GEAR));
		importData.addSelectionListener(new SelectionAdapter() {
			
			@Override
			public void widgetSelected(SelectionEvent e) {
				String oldCurStoreClazz = DataCurrent.getInstance().curStoreClazz;
				TreeItem[] selection = treeViewer.getTree().getSelection();
				if(LOG.isDebugEnabled()) {
					LOG.debug(ArrayUtils.toString(selection));
				}
				
				if(null == selection) return;
				TreeItem treeItem = selection[0];
				if(treeItem.getData() instanceof TreeNode) {
					TreeNode treeNode = (TreeNode) treeItem.getData();
					String databaseName = treeNode.toString();
					if(null == databaseName) return;
					String dbStr = TreeSelectionUtil.getDatabaseName(databaseName);
					DBManager.getInstance().updateHome(dbStr);
					DPLBDBNameUtil.KeyName keyName = DPLBDBNameUtil.getInstance().getKeyNameByDatabaseName(databaseName);
					if(null == keyName) return;
					if(null == keyName.getCurStoreClazz()) return;
					DataCurrent.getInstance().curStoreClazz = keyName.getCurStoreClazz();
				}
				
				FileDialog dialog = new FileDialog(motherland);
				String extensionName = BackThread.IMPORT_FILE_SUFFIX;
				dialog.setText("请选择数据库导出文件");
				dialog.setFilterExtensions(new String[] { extensionName });
				String filterPath = "."; 
				if(null != DataCurrent.getInstance().curDataBasePath) {
					filterPath = 
						DataCurrent.getInstance().curDataBasePath +
						File.separator + 
						BackThread.IMPORT_FOLDER;
				}
				
				dialog.setFilterPath(filterPath);
				
				String open = dialog.open();
				if(null != open) {
					File importFile = Folder.getFile(open);
					DataCurrent.getInstance().curImportFile = importFile;
					if(!importDialog.isOpen()) {
						importDialog.open();
					}
				}
				DataCurrent.getInstance().curStoreClazz = oldCurStoreClazz;
			}
			
		});
		treeViewer.getTree().setMenu(menu_leaf);
		
		
		//////////////////////////////// 查询 ///////////////////////////////////////
		
		
		new MenuItem(menu_leaf, SWT.SEPARATOR);
		
		MenuItem findData = new MenuItem(menu_leaf, SWT.PUSH);
		findData.setText("主键查询");
		findData.setImage(ImageManager.getImage(ImageManager.ICON_FIND_BY_KEY));
		findData.addSelectionListener(new SelectionAdapter() {

			@Override
			public void widgetSelected(SelectionEvent e) {
				String oldCurStoreClazz = DataCurrent.getInstance().curStoreClazz;
				TreeItem[] selection = treeViewer.getTree().getSelection();
				if(LOG.isDebugEnabled()) {
					LOG.debug(ArrayUtils.toString(selection));
				}
				
				if(null == selection) return;
				TreeItem treeItem = selection[0];
				if(treeItem.getData() instanceof TreeNode) {
					TreeNode treeNode = (TreeNode) treeItem.getData();
					String databaseName = treeNode.toString();
					if(null == databaseName) return;
					String dbStr = TreeSelectionUtil.getDatabaseName(databaseName);
					DBManager.getInstance().updateHome(dbStr);
					DPLBDBNameUtil.KeyName keyName = DPLBDBNameUtil.getInstance().getKeyNameByDatabaseName(databaseName);
					if(null == keyName) return;
					if(null == keyName.getCurStoreClazz()) return;
					DataCurrent.getInstance().curStoreClazz = keyName.getCurStoreClazz();
				}
				
				//主键查询点
				queryByKey();
				
				DataCurrent.getInstance().curStoreClazz = oldCurStoreClazz;
			}
			
		});
		treeViewer.getTree().setMenu(menu_leaf);
	}

	private void initTable(TableViewer tableViewer) {
		if(null != tableViewer) {
			tableViewer.setContentProvider(new MikeTableContentProvider());
			tableViewer.setLabelProvider(new MikeTableLabelProvider(tableViewer, secondaryEntityTable));
			tableViewer.setSorter(new MikeTableViewerSorter());
		}
	}
	
	/**
	 * 数据格式罗列
	 * persist#EntityStore#com.mike.bdb.dpl.Inventory
	 * persist#EntityStore#com.mike.bdb.dpl.Inventory#itemName
	 * persist#EntityStore#com.mike.bdb.dpl.Vendor
	 * persist#EntityStore#com.sleepycat.persist.formats
	 * @param databaseName
	 */
	private void appendTableData(String databaseName) {
		
		databaseName = TreeSelectionUtil.getName(databaseName);
		DPLBDBNameUtil.KeyName keyName = DPLBDBNameUtil.getInstance().getKeyNameByDatabaseName(databaseName);
		if(null == keyName) return;
		
		String dbStr = TreeSelectionUtil.getDatabaseName(databaseName);
		DBManager.getInstance().updateHome(dbStr);
		
		if(null == keyName.getCurStoreClazz()) return;
		
		DataCurrent.getInstance().curStoreClazz = keyName.getCurStoreClazz();
		
		boolean containsKey = DataCurrent.openTableViewers.containsKey(databaseName);
		if(containsKey) {
			changeSelectedTableItem(databaseName);
			return;
		}
		
		updataDataCurrent(keyName);
		
		//TODO <!分页> 双击时 自动第一页
		DataCurrent.getInstance().getPageInfo().setIndex(0);
		
		resetPageIndex();
		CTabItem cTabItem = new CTabItem(tabTabFolder, SWT.CLOSE);
		cTabItem.setText(keyName.getPrefix());
		cTabItem.setImage(ImageManager.getImage(ImageManager.ICON_DATABASE));
		cTabItem.setData(databaseName);
		tabTabFolder.addCTabFolder2Listener(new CTabFolder2Adapter() {
			
			@Override
			public void close(CTabFolderEvent e) {
				Object data = e.item.getData();
				DataCurrent.openTableViewers.remove(data.toString());
			}
			
		});
			
		tabTabFolder.setSelection(cTabItem);
		
		//在这里创建TableViewer的
		TableViewer tableViewer = new TableViewer(tabTabFolder, SWT.BORDER | SWT.FULL_SELECTION | SWT.MULTI);
		//容器收集器，用于刷新时获得对象
		HashMap<CTabItem, TableViewer> hashMap = new HashMap<CTabItem, TableViewer>();
		hashMap.put(cTabItem, tableViewer);
		allTabItem.add(hashMap);
		initTable(tableViewer);
		cTabItem.setControl(tableViewer.getTable());
		tableViewer.setInput(null);
		
		if(LOG.isDebugEnabled()) {
			LOG.debug("See :" + keyName.getPrefix() + " - " + keyName.getSuffix());
			LOG.debug("curStoreClazz :" + DataCurrent.getInstance().curStoreClazz);
		}
		
		Table t = tableViewer.getTable();
		TableColumn tableColumn = null;
		int colnumCount = 0;
		List<String> colnumName = new ArrayList<String>();
		methodReturnMap = new HashMap<String, Type>();
		
		
		Class<?> storeClazz = DPLBDBNameUtil.getInstance().getClassByName(keyName.getCurStoreClazz());
		if(null == storeClazz) return;
		
		List<Method> berkeleyAttribute = ReflectUtil.getBerkeleyAttribute(storeClazz);

		for (Method m : berkeleyAttribute) {
			tableColumn = new TableColumn(t, SWT.NONE);
			colnumName.add(m.getName());
			methodReturnMap.put(m.getName(), m.getGenericReturnType());
			tableColumn.setText(m.getName().replace("get", ""));
			tableColumn.setWidth(16 * m.getName().length());
			tableColumn.setMoveable(true);
			addSortListener(tableColumn, tableViewer, m);
			colnumCount ++;
		}
		
		t.setHeaderVisible(true);
		t.setLinesVisible(true);

		// Create the cell editors
	    CellEditor[] editors = new CellEditor[colnumCount + 1];
	    for (int i = 0; i < editors.length; i++) {
	    	editors[i] = new TextCellEditor(t);
		}
	    // Set the editors, cell modifier, and column properties
	    tableViewer.setColumnProperties(colnumName.toArray(new String[0]));
	    tableViewer.setCellModifier(new MikeTableCellModifier(tableViewer, methodReturnMap));
	    tableViewer.setCellEditors(editors);
		tableViewer.setInput(keyName);
		tableViewer.refresh();
		initColor(tableViewer);
		 
		DataCurrent.openTableViewers.put(databaseName, tableViewer);
	}

	private void changeSelectedTableItem(String databaseName) {
		CTabItem[] items = tabTabFolder.getItems();
		for (CTabItem item : items) {
			Object data = item.getData();
			boolean equals = data.toString().equals(databaseName);
			if (equals) {
				tabTabFolder.setSelection(item);
				break;
			}
		}
		return;
	}

	private static volatile Color currentColorOdd = null;
	public static Color getCurrentColorOdd() {
		return currentColorOdd;
	}

	private static volatile Color currentColorEven = null;
	public static Color getCurrentColorEven() {
		return currentColorEven;
	}

	private CTabFolder	dirTabFolder;
	private Spinner pageSpinner;
	
	private void initColor(TableViewer tableViewer) {
		if(null == tableViewer) return;
		Table table = tableViewer.getTable();
		TableItem[] items = table.getItems();
		int index = 0;
		for (TableItem item: items) {
			if (index % 2 != 0) {
				if(null != currentColorEven) item.setBackground(currentColorEven);
			} else {
				if(null != currentColorOdd) item.setBackground(currentColorOdd);
			}
			index++;
		}
	}

	/***
	 * 设置字段的排序监听适配器
	 * @param tableColumn
	 * @param tableViewer
	 * @param m
	 */
	private void addSortListener(TableColumn tableColumn, final TableViewer tableViewer, final Method m) {
		tableColumn.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent event) {
				((MikeTableViewerSorter) tableViewer.getSorter()).doSort(m.getName());
				tableViewer.refresh();
			}
		});
	}

	/**  查询过滤 */
	private void query() {
		if(null == queryDialog) return;
		if(!queryDialog.isOpen()) {
			queryDialog.open();
		}
	}
	
	/**  主键查询过滤 */
	private void queryByKey() {
		if(null == queryByKeyDialog) return;
		if(!queryByKeyDialog.isOpen()) {
			queryByKeyDialog.open();
		}
	}
	
	public void queryPKCondition(Map<Method, Text> methodMap,
			HashMap<String, Type> methodReturnMap) {
		if(null == methodMap || null == methodReturnMap) return;
		if(null == queryPKEntityTable) return;
		if(!queryPKEntityTable.isOpen()) {
			queryPKEntityTable.open(methodMap, methodReturnMap);
		}
	}
	
	public void queryCondition(Map<Method, Text> methodMap,
			HashMap<String, Type> methodReturnMap) {
		if(null == methodMap || null == methodReturnMap) return;
		if(null == queryConditionEntityTable) return;
		if(!queryConditionEntityTable.isOpen()) {
			queryConditionEntityTable.open(methodMap, methodReturnMap);
		}
	}
}
